<template>
  <div id="QiRpt">
    <Breadcrumb content="指标维护" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="35">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-button
                type="text"
                icon="vxe-icon-refresh"
                class="button-blue"
                content="刷新"
                :loading="showLoading"
                @click="findRptList"
              ></vxe-button>
              <vxe-button
                type="text"
                icon="vxe-icon-square-plus"
                class="button-blue"
                content="新增"
                @click="handleAdd(-1)"
              ></vxe-button>
              <vxe-button
                type="text"
                icon="vxe-icon-save"
                class="button-blue"
                content="保存"
                @click="saveList"
              ></vxe-button>
              <vxe-button
                type="text"
                icon="vxe-icon-delete"
                class="button-red"
                content="删除"
                @click="handleDelete"
              ></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="qiRptTableBox">
            <vxe-table
              ref="qiIndexMainTableRef"
              :loading="showLoading"
              class="mytable-scrollbar"
              border
              align="left"
              height="auto"
              :keep-source="true"
              :data="qiIndexIMainList"
              @cell-click="qiRptRowClick"
              :row-config="{ isCurrent: true, isHover: true }"
              :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }"
              :edit-config="{
                trigger: 'click',
                mode: 'row',
                showIcon: true
              }"
              resizable
              show-overflow
            >
              <vxe-column type="checkbox" align="center" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
              <vxe-column
                field="indexCode"
                title="编码"
                width="60px"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.indexCode" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column
                field="indexName"
                title="名称"
                min-width="200px"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.indexName" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column
                field="indexType"
                title="指标类型"
                width="140"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
              >
                <template #edit="{ row }">
                  <vxe-select v-model="row.indexType" placeholder="请选择类型" transfer>
                    <vxe-option value="1" label="检验全过程质量指标"></vxe-option>
                    <vxe-option value="2" label="新增检验全过程质量指标"></vxe-option>
                  </vxe-select>
                </template>
                <template #default="{ row }"> {{ formatIndexType(row) }}</template>
              </vxe-column>
              <vxe-column
                field="dataSource"
                title="数据来源"
                width="80"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
              >
                <template #edit="{ row }">
                  <vxe-select v-model="row.dataSource" placeholder="请选择数据来源" transfer>
                    <vxe-option value="1" label="LIS"></vxe-option>
                    <vxe-option value="2" label="手工"></vxe-option>
                    <vxe-option value="3" label="估算"></vxe-option>
                  </vxe-select>
                </template>
                <template #default="{ row }"> {{ formatDataSource(row) }}</template>
              </vxe-column>
              <vxe-column
                field="seq"
                title="顺序"
                width="50"
                :edit-render="{ autofocus: '.vxe-input--inner' }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.seq" type="text"></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="65">
          <el-tabs type="border-card">
            <el-tab-pane label="项目维护">
              <QiIndexItem ref="qiIndexItemRef"></QiIndexItem>
            </el-tab-pane>
            <el-tab-pane label="专业维护">
              <QiIndexMajor ref="qiIndexMajorRef"></QiIndexMajor>
            </el-tab-pane>
            <el-tab-pane label="操作日志"> <LogInfo requestUrl="/api/qi/" /> </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import QiIndexItem from './QiIndexItem.vue';
import QiIndexMajor from './QiIndexMajor.vue';
import LogInfo from '@/components/LogInfo.vue'; //日志

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let showLoading = ref(false); //左侧刷新+表格加载状态
interface RowVO {
  id: string;
  indexCode: string;
  indexName: string;
  inputCode: string;
  seq: number;
}
// 报表列表
const qiIndexIMainList = reactive([]);
const qiIndexItemRef = ref(null);
const qiIndexMajorRef = ref(null);
const qiIndexMainTableRef = ref(null);

// 方法定义区 =============
onMounted(() => {
  findRptList();
});

// 获取左侧表格数据
function findRptList() {
  showLoading.value = true;
  qiIndexIMainList.length = 0; //放入数据前清空数据
  const url = '/api/qi/report/getQiIndexMainList';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      if (!IsEmpty(res.data)) {
        qiIndexIMainList.push(...res.data);
        qiRptRowClick({ row: qiIndexIMainList[0], rowIndex: 0 });
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      showLoading.value = false;
    });
}

// 添加
async function handleAdd(row?: RowVO | number) {
  const $table = qiIndexMainTableRef.value;
  if ($table) {
    const record = {
      id: null,
      dataSource: '1',
      indexCode: '',
      indexName: '',
      indexType: '',
      seq: ''
    };
    const { row: newRow } = await $table.insertAt(record, row);
    await $table.setEditRow(newRow);
    $table.setCurrentRow(newRow);
  }
}

//批量保存
function saveList() {
  const $xTable = proxy.$refs.qiIndexMainTableRef as any;
  const arrModifies = $xTable.getUpdateRecords();
  const arrNews = $xTable.getInsertRecords();
  arrNews.forEach((item: any, idx) => {
    const url = '/api/qi/report/addQiIndexMain';
    const data = item;
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
          findRptList();
        }
      })
      .catch((err) => {
        if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
          VxeMessage(err, VxeNotifyType.error);
        }
      });
  });
  arrModifies.forEach((item, idx) => {
    const url = '/api/qi/report/updateQiIndexMain';
    const data = item;
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (idx === arrModifies.length - 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
          findRptList();
        }
      })
      .catch((err) => {
        if (idx === arrModifies.length - 1) {
          VxeMessage(err, VxeNotifyType.error);
        }
      });
  });
}

// 删除
function handleDelete() {
  const $xTable = proxy.$refs.qiIndexMainTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        selectRows.forEach((item, idx) => {
          const url = '/api/qi/report/deleteQiIndexMain';
          proxy.$http
            .post(url, item)
            .then((res: any) => {
              if (idx === selectRows.length - 1) {
                VxeMessage('删除成功', VxeNotifyType.success);
                findRptList();
              }
            })
            .catch((err) => {
              VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
            });
        });
      }
    });
}
// 点击表格当前行
function qiRptRowClick({ row, rowIndex }) {
  proxy.$nextTick(() => {
    qiIndexItemRef.value?.findqiIndexIMainList(row.id);
    qiIndexItemRef.value?.getQiIndexMajorList(row.id);
    qiIndexMajorRef.value?.findqiIndexMajorList(row.id);
  });
  proxy.$refs.qiIndexMainTableRef.setCurrentRow(row);
}

function formatDataSource(row: any) {
  if (row.dataSource === '1') {
    return 'LIS';
  } else if (row.dataSource === '2') {
    return '手工';
  } else if (row.dataSource === '3') {
    return '估算';
  } else {
    return '';
  }
}

function formatIndexType(row: any) {
  return row.indexType === '1' ? '检验全过程质量指标' : '新增检验全过程质量指标';
}
</script>

<style lang="scss" scoped>
#QiRpt {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .qiRptTableBox {
        height: calc(100% - 40px);
      }
      .el-tabs {
        height: 100%;
      }
      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0;
        .el-tab-pane {
          height: 100%;
        }
      }
    }
  }
}
</style>
